package com.jungle.client.control;

import javafx.scene.control.TableCell;
import javafx.scene.input.KeyCode;
import javafx.util.converter.DefaultStringConverter;

public class ImeTextFieldTableCell<S, T> extends TableCell<S, T> {
    private TextField textField;
    private DefaultStringConverter converter;

    public ImeTextFieldTableCell() {
        this.converter = new DefaultStringConverter();
    }

    @Override
    public void startEdit() {
        if (!isEditable() || !getTableView().isEditable() || !getTableColumn().isEditable()) {
            return;
        }
        super.startEdit();

        if (textField == null) {
            textField = new TextField();
            textField.setOnAction(event -> commitEdit((T) textField.getText()));
            textField.setOnKeyReleased(event -> {
                if (event.getCode() == KeyCode.ESCAPE) {
                    cancelEdit();
                }
            });
        }

        textField.setText(getItem() == null ? "" : getItem().toString());
        setText(null);
        setGraphic(textField);
        textField.requestFocus();
        textField.selectAll();
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        setText(getItem() == null ? "" : getItem().toString());
        setGraphic(null);
    }

    @Override
    protected void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (textField != null) {
                    textField.setText(getItem() == null ? "" : getItem().toString());
                }
                setText(null);
                setGraphic(textField);
            } else {
                setText(getItem() == null ? "" : getItem().toString());
                setGraphic(null);
            }
        }
    }
}
